package com.surrealbananapeel.battleship;

import java.util.ArrayList;

/**
 * This class is responsible for determining the layout of our board. It is 
 * based off statistics from previous games.
 * 
 * @author Emmett Little and Alberto Saavedra
 */
public class Layout
{
    private Ship[] ships;
    private Match match;
    
    /**
     * Create a new layout object.
     */
    public Layout()
    {
        this.match = Match.getInstance();
        ships = Fleet.getShips();
        randomize();
    }
    
    /**
     * This is responsible for randomising the ships. It does that by 
     * moving the ship to a random spot and then seeing if it intersects 
     * with any other ships or highly shot at points if it does randomise
     * again.
     */
    private void randomize()
    {
        ArrayList<Point> shots = (ArrayList<Point>) this.match.getOppStats();
        while (shots.size() > 40)
        {
            shots.remove(shots.size() - 1);
        }
        for (int i = 0; i < ships.length; i++)
        {
            ships[i].randomize();
            
            for (int j = 0; j < i; j++)
            {
                int counter = 0;
                while (ships[i].intersect(ships[j]) > 0 || 
                        (++counter < 100 && intersectPoints(ships[i], shots)))
                {
                    ships[i] = Fleet.getShip(ships[i].getName());
                    ships[i].randomize();
                    j = 0;
                }
            }
        }
    }
    
    /**
     * This will determine if the supplied ship and points overlap. If they 
     * do then true is returned, otherwise false is returned.
     * 
     * @param ship The ship to check intersections with
     * @param points The points to check intersections with
     * @return True if the ship intersects the points, false otherwise
     */
    private boolean intersectPoints(Ship ship, ArrayList<Point> points)
    {
        boolean result = false;
        Point[] shipPoints = ship.getPoints();
        for (int i = 0; i < points.size() && !result; i++)
        {
            for (int j = 0; j < shipPoints.length && !result; j++)
            {
                if (points.get(i).equals(shipPoints[j]))
                {
                    result = true;
                }
            }
        }
        return result;
    }
    
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString()
    {
        String result = "";
        for (int i = 0; i < ships.length; i++)
        {
            result += ships[i].toString();
            if (i != ships.length - 1)
                result += "|";
        }
        return result;
    }
}
